<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>红豆面包留言板</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
    }
    .container {
      max-width: 900px;
      margin: 50px auto;
      padding: 30px;
      background: white;
      box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
    }
    h2 {
      text-align: center;
      color: #333;
      font-size: 2rem;
      margin-bottom: 20px;
    }
    .search-box {
      margin-bottom: 20px;
      display: flex;
      gap: 15px;
      justify-content: space-between;
    }
    .search-box input[type="text"] {
      flex: 1;
      padding: 12px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 1rem;
    }
    .search-box button {
      padding: 12px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1rem;
    }
    .search-box button:hover {
      background-color: #45a049;
    }
    .message-form {
      display: flex;
      gap: 10px;
      margin-bottom: 30px;
    }
    .message-form input[type="text"] {
      flex: 1;
      padding: 12px;
      border: 1px solid #ddd;
      border-radius: 5px;
      font-size: 1rem;
    }
    .message-form button {
      padding: 12px;
      background-color: #2196F3;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1rem;
    }
    .message-form button:hover {
      background-color: #1E88E5;
    }
    .message-list {
      list-style: none;
      padding: 0;
      margin: 0;
    }
    .message-item {
      padding: 15px;
      border: 1px solid #ddd;
      border-radius: 5px;
      margin-bottom: 20px;
      display: flex;
      flex-direction: column;
      background-color: #fafafa;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
    .message-item .header {
      display: flex;
      justify-content: space-between;
      font-weight: bold;
      color: #333;
      margin-bottom: 10px;
    }
    .message-item .content {
      font-size: 1.1rem;
      color: #555;
      margin-bottom: 10px;
    }
    .message-item .footer {
      font-size: 0.9rem;
      color: #888;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .message-item button {
      background-color: #f44336;
      color: white;
      border: none;
      border-radius: 5px;
      padding: 6px 12px;
      cursor: pointer;
    }
    .message-item button:hover {
      background-color: #d32f2f;
    }
    .pagination {
      text-align: center;
      margin-top: 20px;
    }
    .pagination button {
      padding: 10px;
      background-color: #2196F3;
      color: white;
      border: none;
      border-radius: 5px;
      margin: 0 5px;
      cursor: pointer;
    }
    .pagination button:hover {
      background-color: #1E88E5;
    }
  </style>
</head>
<body>
<div class="container">
  <!-- 登出按钮 -->
  <div class="logout-container" style="text-align: right; margin-bottom: 20px;">
    <button id="logout-button">登出</button>
  </div>

  <h2>红豆面包留言板系统</h2>

  <!-- 搜索框 -->
  <div class="search-box">
    <input type="text" id="search-keyword" placeholder="请输入关键词搜索留言">
    <button id="search-mine">搜索我的留言</button>
    <button id="search-all">搜索所有留言</button>
  </div>

  <!-- 留言输入框 -->
  <div class="message-form">
    <input type="text" id="message-input" placeholder="请输入留言内容">
    <button id="submit-message">留言</button>
  </div>

  <!-- 留言列表 -->
  <ul class="message-list" id="message-list">
    <!-- 动态加载留言 -->
  </ul>

  <!-- 分页控制 -->
  <div class="pagination">
    <button id="prev-page">上一页</button>
    <button id="next-page">下一页</button>
  </div>
</div>

<script>
  document.addEventListener("DOMContentLoaded", () => {
    const messageList = document.getElementById("message-list");
    const prevPageButton = document.getElementById("prev-page");
    const nextPageButton = document.getElementById("next-page");
    let currentPage = 1;
    let currentKeyword = ""; // 用于存储当前搜索的关键词
    const pageSize = 5;
    let tag=0;





    // // 加载留言列表
    // function loadMessages(page = 1) {
    //   fetch(`http://localhost:8080/messages/allmessages?page=${page}`, {
    //     method: "GET",
    //     headers: {
    //       "Authorization": `Bearer ${localStorage.getItem("jwtToken")}`
    //     }
    //   })
    //     .then(response => response.json())
    //     .then(data => {
    //       console.log(data);
    //
    //       messageList.innerHTML = "";
    //       if (data.length === 0) {
    //         messageList.innerHTML = "<li>没有找到相关留言！</li>";
    //       } else {
    //         data.forEach((message) => {
    //           const li = document.createElement("li");
    //           li.className = "message-item";
    //           li.innerHTML = `
    //           <div class="header">
    //             <span>${message.username}</span>
    //             <span>${message.createdAt}</span>
    //           </div>
    //           <div class="content">${message.content}</div>
    //           <div class="footer">
    //             <button data-id="${message.id}" class="delete-btn">删除</button>
    //           </div>
    //         `;
    //           messageList.appendChild(li);
    //         });
    //       }
    //     })
    //     .catch(error => console.error("Failed to load messages:", error));
    // }
// 加载留言列表
    function loadMessages(page = 1, keyword = "") {

      const url = keyword
        ? `http://localhost:8080/messages/searchall?keyword=${encodeURIComponent(keyword)}&page=${page}`
        : `http://localhost:8080/messages/allmessages?page=${page}`;

      fetch(url, {
        method: "GET",
        headers: {
          "Authorization": `Bearer ${localStorage.getItem("jwtToken")}`
        }
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
          messageList.innerHTML = "";
          if (data.length === 0) {
            messageList.innerHTML = "<li>没有找到相关留言！</li>";
          } else {
            data.forEach((message) => {

              const li = document.createElement("li");
              li.className = "message-item";
              li.innerHTML = `
              <div class="header">
                <span>${message.username}</span>
                <span>${message.createdAt}</span>
              </div>
              <div class="content">${message.content}</div>
              <div class="footer">
                <button data-id="${message.id}" class="delete-btn">删除</button>
              </div>
            `;
              messageList.appendChild(li);
            });
          }
        })
        .catch(error => console.error("Failed to load messages:", error));
    }
    // 删除留言
    messageList.addEventListener("click", (event) => {
      if (event.target.classList.contains("delete-btn")) {
        const messageId = event.target.getAttribute("data-id");
        if (confirm("确定要删除这条留言吗？")) {
          fetch(`http://localhost:8080/messages/${messageId}`, {
            method: "DELETE",
            headers: {
              "Authorization": `Bearer ${localStorage.getItem("jwtToken")}`
            }
          })
            .then(() => loadMessages(currentPage))
            .catch((error) => console.error("Failed to delete message:", error));
        }
      }
    });

    // // 下一页
    // nextPageButton.addEventListener("click", () => {
    //   currentPage++;
    //   loadMessages(currentPage);
    // });
    //
    // // 上一页
    // prevPageButton.addEventListener("click", () => {
    //   if (currentPage > 1) {
    //     currentPage--;
    //     loadMessages(currentPage);
    //   }
    // });

    // 提交留言
    document.getElementById("submit-message").addEventListener("click", () => {
      const messageInput = document.getElementById("message-input");
      const content = messageInput.value.trim();
      if (!content) {
        alert("留言内容不能为空！");
        return;
      }
      fetch("http://localhost:8080/messages", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${localStorage.getItem("jwtToken")}`
        },
        body: JSON.stringify({ content })
      })
        .then(() => {
          messageInput.value = "";
          loadMessages(currentPage);
        })
        .catch((error) => console.error("Failed to submit message:", error));
    });

    // 初始化加载第一页留言
    loadMessages(currentPage);

    // // 加载“全部关键词留言”函数
    // function loadAllMessages(keyword) {
    //
    //   fetch(`http://localhost:8080/messages/searchall?keyword=${keyword}`, {
    //     method: "GET",
    //     headers: {
    //       "Authorization": `Bearer ${localStorage.getItem("jwtToken")}`,
    //     },
    //   })
    //     .then((response) => response.json())
    //     .then((data) => {
    //       messageList.innerHTML = "";
    //       if (data.length === 0) {
    //         messageList.innerHTML = "<li>没有找到相关留言！</li>";
    //       } else {
    //         data.forEach((message) => {
    //           const li = document.createElement("li");
    //           li.className = "message-item";
    //           li.innerHTML = `
    //           <div class="header">
    //             <span>${message.username}</span>
    //             <span>${message.createdAt}</span>
    //           </div>
    //           <div class="content">${message.content}</div>
    //         `;
    //           messageList.appendChild(li);
    //         });
    //       }
    //     })
    //     .catch((error) => console.error("Failed to load my messages:", error));
    // }
    // // 绑定“搜索全部留言”按钮
    // document.getElementById("search-all").addEventListener("click", () => {
    //   const keywordInput = document.getElementById("search-keyword").value.trim();
    //   loadAllMessages(keywordInput);
    // });

    // 搜索所有留言
    document.getElementById("search-all").addEventListener("click", () => {
      tag=0;
      const keywordInput = document.getElementById("search-keyword").value.trim();
      currentKeyword = keywordInput; // 保存关键词
      currentPage = 1; // 重置页码
      loadMessages(currentPage, currentKeyword);
    });

    // 加载“我的关键词留言”函数
    function loadMyMessages(page=1,keyword) {

      fetch(`http://localhost:8080/messages/search?keyword=${keyword}&page=${page}`, {
        method: "GET",
        headers: {
          "Authorization": `Bearer ${localStorage.getItem("jwtToken")}`,
        },
      })
        .then((response) => response.json())
        .then((data) => {
          messageList.innerHTML = "";
          if (data.length === 0) {
            messageList.innerHTML = "<li>没有找到相关留言！</li>";
          } else {
            data.forEach((message) => {

              const li = document.createElement("li");
              li.className = "message-item";
              li.innerHTML = `
              <div class="header">
                <span>${message.username}</span>
                <span>${message.createdAt}</span>
              </div>
              <div class="content">${message.content}</div>
               <div class="footer">
                <button data-id="${message.id}" class="delete-btn">删除</button>
              </div>
            `;
              messageList.appendChild(li);
            });
          }
        })
        .catch((error) => console.error("Failed to load my messages:", error));
    }

    // 绑定“搜索我的留言”按钮
    document.getElementById("search-mine").addEventListener("click", () => {
      tag=1;
      const keywordInput = document.getElementById("search-keyword").value.trim();
      currentKeyword = keywordInput; // 保存关键词
      currentPage = 1; // 重置页码
      loadMyMessages(currentPage,currentKeyword);
    });
// // 搜索自己留言
//     document.getElementById("search-mine").addEventListener("click", () => {
//       const keywordInput = document.getElementById("search-keyword").value.trim();
//       currentKeyword = keywordInput; // 保存关键词
//       currentPage = 1; // 重置页码
//       tag=1;
//       const url = `http://localhost:8080/messages/search?keyword=${encodeURIComponent(currentKeyword)}&page=${currentPage}`;
//       fetch(url, {
//         method: "GET",
//         headers: {
//           "Authorization": `Bearer ${localStorage.getItem("jwtToken")}`
//         }
//       })
//         .then(response => response.json())
//         .then(data => {
//           console.log(data);
//           messageList.innerHTML = ""; // 清空现有留言列表
//           if (data.length === 0) {
//             messageList.innerHTML = "<li>没有找到相关留言！</li>";
//           } else {
//             data.forEach((message) => {
//               const li = document.createElement("li");
//               li.className = "message-item";
//               li.innerHTML = `
//             <div class="header">
//               <span>${message.username}</span>
//               <span>${message.createdAt}</span>
//             </div>
//             <div class="content">${message.content}</div>
//             <div class="footer">
//               <button data-id="${message.id}" class="delete-btn">删除</button>
//             </div>
//           `;
//               messageList.appendChild(li);
//             });
//           }
//         })
//         .catch(error => console.error("Failed to load my messages:", error));
//     });

    // // 搜索我的留言
    // document.getElementById("search-mine").addEventListener("click", () => {
    //   alert("当前实现只支持搜索所有留言，未实现搜索我的留言的分页功能！");
    // });
    // // 上一页
    // prevPageButton.addEventListener("click", () => {
    //   if (currentPage > 1) {
    //     currentPage--;
    //     loadMessages(currentPage);
    //   } else {
    //     alert("已经是第一页！");
    //   }
    // });
    //
    // // 下一页
    // nextPageButton.addEventListener("click", () => {
    //   currentPage++;
    //   loadMessages(currentPage);
    // });
// 分页操作
    prevPageButton.addEventListener("click", () => {
      if (currentPage > 1) {
        currentPage--;
        if(tag){
          loadMyMessages(currentPage,currentKeyword)
        }
        else{
          loadMessages(currentPage, currentKeyword);
        }

      } else {
        alert("已经是第一页！");
      }
    });

    nextPageButton.addEventListener("click", () => {
      currentPage++;
      if(tag){
        loadMyMessages(currentPage,currentKeyword);
      }
      else{
        loadMessages(currentPage, currentKeyword);
      }
    });
    // 登出功能
    const logoutButton = document.getElementById("logout-button");
    logoutButton.addEventListener("click", () => {
      localStorage.removeItem("jwtToken");  // 清除令牌
      window.location.href = "user.html";    // 跳转到user.html
    });

  });
</script>

</body>
</html>
